package org.example;

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.Scanner;


/**
 * Created with IntelliJ IDEA.
 * Description: DataSource测试
 * User: 王圆豪
 * Date: 2025-04-13
 * Time: 15:05
 */
public class Demo02_DataSource {
    public static void main(String[] args) {
        //定义MySQL数据源对象
        MysqlDataSource mysqlDataSource =  new MysqlDataSource();
        //设置数据库连接串
        mysqlDataSource.setURL("jdbc:mysql://127.0.0.1" +
                ":3306/java113?characterEncoding=utf8&allowPublicKeyRetr" +
                "ieval=true&useSSL=false");
        //用户名
        mysqlDataSource.setUser("root");
        //密码
        mysqlDataSource.setPassword("123456");
        //定义JDBC的数据源对象
        DataSource dataSource = mysqlDataSource;
        //定义连接对象
        Connection connection = null;
        //定义预处理SQL执行对象
        PreparedStatement statement = null;
        //定义结果集对象
        ResultSet resultSet = null;

        try {
            //1. 通过数据源获取数据库连接
            connection = dataSource.getConnection();
            //2.获取预处理SQL执行对象
            //定义要执行的SQL语句
            String sql = "select id, name, email, class_id from student where name = ?";
            statement = connection.prepareStatement(sql);
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入你要查询的姓名：");
            String name = sc.next();
            //3. 用真实值代替占位符
            statement.setString(1,name);
            //4. 执行sql并且返回结果集
            resultSet = statement.executeQuery();
            //5. 遍历结果集
            while(resultSet.next()){
                long stuId = resultSet.getLong(1);
                String stuName = resultSet.getString(2);
                String stuMail = resultSet.getString(3);
                long stuClassId = resultSet.getLong(4);
                System.out.println(MessageFormat.format("学生编号={0}, 学生姓名={1}, 学生邮箱={2}, 学生班级={3}",
                        stuId,stuName,stuMail,stuClassId));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
